package gov.kqqzyyy.monkey.orderpad.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.adapter.OrderGroupDetailAdapter;
import gov.kqqzyyy.monkey.orderpad.adapter.OrderGroupTitleAdapter;
import gov.kqqzyyy.monkey.orderpad.adapter.OrderSelectedAdapter;
import gov.kqqzyyy.monkey.orderpad.adapter.TasteAdapter;
import gov.kqqzyyy.monkey.orderpad.mytools.DateTimeUtil;
import gov.kqqzyyy.monkey.orderpad.mytools.FtpUtil;
import gov.kqqzyyy.monkey.orderpad.mytools.NetWorkUtil;
import gov.kqqzyyy.monkey.orderpad.mytools.PhoneFormatCheckUtils;
import gov.kqqzyyy.monkey.orderpad.mytools.UploadListener;
import gov.kqqzyyy.monkey.orderpad.network.RetrofitUtil;
import gov.kqqzyyy.monkey.orderpad.network.base.BaseObserver;
import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.orderpad.object.DC_CPXX;
import gov.kqqzyyy.monkey.orderpad.object.DC_KWBZ;
import gov.kqqzyyy.monkey.orderpad.object.FloorPatient;
import gov.kqqzyyy.monkey.orderpad.object.FloorsAndBeds;
import gov.kqqzyyy.monkey.orderpad.object.MRCPXX;
import gov.kqqzyyy.monkey.orderpad.object.MenuDetail;
import gov.kqqzyyy.monkey.orderpad.object.SelectedDish;
import gov.kqqzyyy.monkey.orderpad.object.XTGL;
import gov.kqqzyyy.monkey.orderpad.object.post_param.StoredOrder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

//点餐ACTIVITY
@SuppressLint("NonConstantResourceId")
public class OrderMenuActivity extends NavigationBaseActivity implements View.OnClickListener, Spinner.OnItemSelectedListener, AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {

    @BindView(R.id.container)
    FrameLayout container;

    ListView mGroupTitleListView;
    RecyclerView mMenuDetailRecyclerView;
    RecyclerView mSelectedRecyclerView;
    Button mPayBtn, mCheckBtn, mCleanBtn, mStoredBtn, mFlushBtn;
    Spinner mDishSpinner, mFloorSpinner, mBedSpinner;
    TextView mTotalPrice, mDietTitle, mDeliveryText, mPatientBed, mPatientName, mPatientSex, mPatientPhone, mPatientDietType;
    SearchView mSearchView;

    private LinearLayoutManager layoutManager;

    private OrderGroupDetailAdapter mMenuDetailAdapter;
    private OrderGroupTitleAdapter mGroupTitleAdapter;
    private OrderSelectedAdapter mOrderSelectedAdapter;

    private List<MenuDetail> mMenuDetailList;
    private List<SelectedDish> mSelectedList;
    private List<MRCPXX> mResultList;

    private String mDDHDate; //订单号日期
    private int mDDHCC;//订单号餐次 1：早，2：中，3：晚
    private double totalPrice;
    private List<String> mDDHList;

    private String delivery_time;

    static int DEVICE_TYPE = 2;//设备类型，1：电视 2：移动设备

    private FloorPatient choosePatient;
    DecimalFormat df = new DecimalFormat("#####0.00");

    private String DDKWBZ;//订单口味备注
    private String zffs = "jz";
    private String Dcr;
    private String Lxdh;

    private SubmitDialogFragment submitDialogFragment;

    private BaseObserver<List<FloorsAndBeds>> floorObserver;
    private BaseObserver<List<MRCPXX>> mrcpObserver;

    private final Handler myHandler = new Handler();
    private final Runnable mLoadingRunnable = this::loadView;

    private SparseArray<List<MRCPXX>> cpxxArray;

    private Thread ftpThread;
    private UploadListener uploadListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        cpxxArray = new SparseArray<>();
        uploadListener = (currentStep, uploadSize, file) -> {
            switch (currentStep) {
                case FtpUtil.FTP_UPLOAD_SUCCESS:
                    KLog.d("APE", file.getName() + FtpUtil.FTP_UPLOAD_SUCCESS);
                    break;
                case FtpUtil.FTP_UPLOAD_LOADING:
                    long fize = file.length();
                    float num = (float) uploadSize / (float) fize;
                    int result = (int) (num * 100);
                    KLog.d("APE", FtpUtil.FTP_UPLOAD_LOADING + ":" + result);
                    break;
                case FtpUtil.FTP_DISCONNECT_SUCCESS:
                    KLog.d("APE", "upload disconnect, stop thread");
                    stopUploadThread();
                    break;
                case FtpUtil.FTP_CONNECT_FAIL:
                    KLog.d("APE", FtpUtil.FTP_CONNECT_FAIL);
                    break;
                case FtpUtil.FTP_UPLOAD_FAIL:
                    KLog.d("APE", FtpUtil.FTP_UPLOAD_FAIL);
                    break;
            }
        };
    }

    private void doUploadImgs() {
        FtpUtil ftpUtil = new FtpUtil();
        String path = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath();
        File picDir = new File(path);
        if (picDir.isDirectory()) {
            File[] files = picDir.listFiles();
            if (files.length > 0) {
                LinkedList<File> fileList = new LinkedList<>();
                Collections.addAll(fileList, Objects.requireNonNull(files));
                ftpThread = new Thread(() -> {
                    try {
                        ftpUtil.uploadMultiFile(fileList, uploadListener, true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                ftpThread.start();
            }
        }
    }

    private void stopUploadThread() {
        if (ftpThread != null && ftpThread.isAlive()) {
            ftpThread.interrupt();
            ftpThread = null;
        }
    }

    private void onBindUI() {
        mGroupTitleListView = findViewById(R.id.order_menugroup_listview);
        mMenuDetailRecyclerView = findViewById(R.id.order_menudetail_recyclerview);
        mSelectedRecyclerView = findViewById(R.id.order_choosed_recyclerview);
        mStoredBtn = findViewById(R.id.order_stored_detail_btn);
        mPayBtn = findViewById(R.id.order_pay_btn);
        mCheckBtn = findViewById(R.id.order_submit_detail_btn);
        mCleanBtn = findViewById(R.id.order_clean_btn);
        mDishSpinner = findViewById(R.id.order_dish_spinner);
        mTotalPrice = findViewById(R.id.order_total_price);
        mDietTitle = findViewById(R.id.order_diet_title);
        mDeliveryText = findViewById(R.id.order_deliver_time);
        mPatientBed = findViewById(R.id.order_patient_bednum);
        mPatientName = findViewById(R.id.order_patient_name);
        mPatientSex = findViewById(R.id.order_patient_sex);
        mPatientPhone = findViewById(R.id.order_patient_phone);
        mPatientDietType = findViewById(R.id.order_patient_diettype);
        mBedSpinner = findViewById(R.id.order_bed_choose_spinner);
        mFloorSpinner = findViewById(R.id.order_floor_choose_spinner);
        mSearchView = findViewById(R.id.order_search_view);
        mFlushBtn = findViewById(R.id.order_flush_btn);
        setmFloorSpinner(mFloorSpinner);
        setmBedSpinner(mBedSpinner);
    }

    private void loadView() {
        container.removeAllViews();
        LayoutInflater.from(this).inflate(R.layout.activity_order_menu, container);
        onBindUI();
        mGroupTitleAdapter = new OrderGroupTitleAdapter(this);
        mGroupTitleListView.setAdapter(mGroupTitleAdapter);
        layoutManager = new LinearLayoutManager(this);
        mMenuDetailRecyclerView.setLayoutManager(layoutManager);
        mMenuDetailAdapter = new OrderGroupDetailAdapter(this);
        mMenuDetailRecyclerView.setAdapter(mMenuDetailAdapter);
        mOrderSelectedAdapter = new OrderSelectedAdapter(this);
        mSelectedRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mSelectedRecyclerView.setAdapter(mOrderSelectedAdapter);
        mCheckBtn.setOnClickListener(this);
        mCleanBtn.setOnClickListener(this);
        mPayBtn.setOnClickListener(this);
        mStoredBtn.setOnClickListener(this);
        mFlushBtn.setOnClickListener(this);
        mDishSpinner.setOnItemSelectedListener(this);
        mBedSpinner.setOnItemSelectedListener(this);
        mFloorSpinner.setOnItemSelectedListener(this);
        mGroupTitleListView.setOnItemClickListener(this);
        mSearchView.setOnQueryTextListener(this);

        if (checkOverTime()) {
            String appJssj = getMyApplication().getJssj();
            KLog.d("APE", appJssj);
            new AlertDialog.Builder(this)
                    .setTitle("点餐提示")
                    .setMessage("点餐时间为" + appJssj + "之前，当前时间不在点餐时段！")
                    .setPositiveButton("确定", (dialogInterface, i) -> finish()).show();
        } else {
            doGetFloorsAndBeds();
        }

        doUploadImgs();
    }

    private void doGetFloorsAndBeds() {
        KLog.d("APE","获取病区信息");
        showProgressDialog("获取病区信息中");
        String param = getMyApplication().getXtgl().getFzlc();
        Observable<BaseResponse<List<FloorsAndBeds>>> observable = RetrofitUtil.getInstence().getFloorsAndBeds(param);
        floorObserver = new BaseObserver<List<FloorsAndBeds>>() {
            @Override
            protected void onSuccees(BaseResponse<List<FloorsAndBeds>> t) {
                cancelProgressDialog();
                doFilterFloorData(t.getData());
                getMyApplication().setmFloorList(t.getData());
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                KLog.d("APE", "获取楼层床位数据失败：" + e);
            }

            @Override
            protected void onCodeError(BaseResponse<List<FloorsAndBeds>> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                KLog.d("APE", "获取楼层床位数据失败\n错误代码：" + t.getCode() + "\n错误信息：" + t.getMsg());
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(floorObserver);

    }

    private void doFilterFloorData(List<FloorsAndBeds> oriList) {
        Set<String> lcSet = new HashSet<>(); //楼层集
        ArrayMap<String, List<String>> lcchArrayMap = new ArrayMap<>(); //楼层房间集
        ArrayMap<String, List<String>> lcbrArrayMap = new ArrayMap<>(); //房间病人集
        List<String> mlcchList;
        List<String> mlcbrList;
        for (FloorsAndBeds floorInfo : oriList
        ) {
            String lcmc = floorInfo.getLcmc();
            if (lcSet.add(lcmc)) {
                mlcchList = new ArrayList<>();
                mlcbrList = new ArrayList<>();
            } else {
                mlcchList = lcchArrayMap.get(lcmc);
                mlcbrList = lcbrArrayMap.get(lcmc);
            }
            String ch = floorInfo.getCh();
            String brbh = floorInfo.getBrbh();
            if (!brbh.equals("0")) {
                Objects.requireNonNull(mlcchList).add(ch);
                Objects.requireNonNull(mlcbrList).add(brbh);
            }
            lcchArrayMap.put(lcmc, mlcchList);
            lcbrArrayMap.put(lcmc, mlcbrList);
        }
        List<String> mFloorList = new ArrayList<>(lcSet);
        Collections.sort(mFloorList, String::compareTo);
        getMyApplication().setmFloorsNameList(mFloorList);
        getMyApplication().setLcchArrayMap(lcchArrayMap);
        getMyApplication().setLcbrArrayMap(lcbrArrayMap);
        setFloor();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().getDecorView().post(() -> myHandler.post(mLoadingRunnable));
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mrcpObserver != null) {
            mrcpObserver.doCancelRequest();
        }
        if (floorObserver != null) {
            floorObserver.doCancelRequest();
        }
    }

    private void setPatientInfo(FloorPatient patient) {
        String bed = "床号：";
        String name = "姓名：";
        String sex = "性别：";
        String phone = "电话：";
        String dietType = "饮食：";
        if (patient != null) {
            bed += getChooseCH();
            name += patient.getBrxm();
            sex += patient.getBrxb().equals("1") ? "男" : "女";
            phone += patient.getLxdh();
            dietType += patient.getYlsx();
        }
        mPatientBed.setText(bed);
        mPatientName.setText(name);
        mPatientSex.setText(sex);
        mPatientPhone.setText(phone);
        mPatientDietType.setText(dietType);
    }

    public void setZffs(String zffs) {
        this.zffs = zffs;
    }

    public void setDDKWBZ(String DDKWBZ) {
        this.DDKWBZ = DDKWBZ;
    }

    public void setDcr(String dcr) {
        Dcr = dcr;
    }

    public void setLxdh(String lxdh) {
        Lxdh = lxdh;
    }

    //是否在点餐时间内
    private boolean checkOverTime() {
        Date dateNow = new Date();
        dateNow.setTime(dateNow.getTime() + getMyApplication().getDeleta());
        String today = DateTimeUtil.getDFFormatString(dateNow);
        String appQssj = getMyApplication().getQssj();
        String dcqssj = "00:00:00";
        if (!appQssj.equals("")) {
            dcqssj = appQssj;
        }
        String appJssj = getMyApplication().getJssj();
        String dcjssj = "16:00:00";
        if (!appJssj.equals("")) {
            dcjssj = appJssj;
        }
        Date endDate = DateTimeUtil.getDTFormatDateTime(today + " " + dcjssj);
        Date startDate = DateTimeUtil.getDTFormatDateTime(today + " " + dcqssj);
        return !(endDate != null && startDate != null && dateNow.getTime() >= startDate.getTime() && dateNow.getTime() <= endDate.getTime());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_pay_btn:
                if (choosePatient == null) {
                    showToast("请选择病人");
                } else if (mSelectedList != null && Objects.requireNonNull(mSelectedList).size() > 0) {
                    String path = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath();
                    NetWorkUtil.getNetInfo();
                    String fileName = getMyApplication().getXtgl().getYhgh() + "_"
                            + getMyApplication().getChooseCH() + "_"
                            + choosePatient.getZyhm() + "_"
                            + NetWorkUtil.MAC_ADD.replace(":","") + "_"
                            + DateTimeUtil.getDateFormat(new Date()) + ".png";
                    try {
                        //截图
                        View shotView = getWindow().getDecorView();
                        shotView.destroyDrawingCache();
                        shotView.setDrawingCacheEnabled(true);
                        shotView.buildDrawingCache();
                        Bitmap bitmap = shotView.getDrawingCache();
                        //保存图片
                        FileOutputStream fos = new FileOutputStream(path + File.separator + fileName);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        KLog.d("APE", "屏幕截图异常：" + e.toString());
                    }
                    new Handler().postDelayed(() -> {
                        showSubmitDialog(YSLXCheck());//菜单中有病人忌口，弹出提醒
                    }, 500);
                }
                break;
            case R.id.order_submit_detail_btn:
                Intent intent1 = new Intent(this, OrderCheckActivity2.class);
                startActivity(intent1);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.order_clean_btn:
                closeSearchView();
                cleanSelected();
                break;
            case R.id.order_stored_detail_btn:
                Intent intent2 = new Intent(this, StoredOrderActivity.class);
                startActivity(intent2);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.order_flush_btn:
                closeSearchView();
                doGetMRCP(mDDHCC);
                break;
        }
    }

    private void closeSearchView() {
        if (mSearchView.hasFocus()) {
            mSearchView.onActionViewCollapsed();
        }
    }

    //提交订单
    public void doSaveOrSubmitNewOrder() {
        if (choosePatient != null) {
            String DDH_HEAD = choosePatient.getBrbh() + DEVICE_TYPE + mDDHDate + mDDHCC;
            int ddCount;
            int maxEnd = 0;
            if (mDDHList.size() > 0) {
                for (String ddh : mDDHList) {
                    if (ddh.startsWith(DDH_HEAD)) {
                        ddCount = Character.getNumericValue(ddh.charAt(ddh.length() - 1));
                        if (ddCount == 9) {
                            Toast.makeText(getApplicationContext(), "该时段订餐次数已到上限9次", Toast.LENGTH_SHORT).show();//该时段订餐次数已到上限9次
                            return;
                        } else {
                            maxEnd = Math.max(ddCount, maxEnd);
                        }
                    }
                }
            }
            maxEnd++;
            String newDDH = DDH_HEAD + maxEnd;
            Gson gson = new Gson();
            String upjson = gson.toJson(mSelectedList);
            String ddkwbz = DDKWBZ == null ? "" : DDKWBZ;
            String XDSJ = DateTimeUtil.getNewServerTime(getMyApplication().getDeltaTime());
            doSubmitOrder(getChooseCH(), choosePatient.getBrbh(), delivery_time, XDSJ, newDDH, upjson, df.format(totalPrice), ddkwbz, getMyApplication().getChooseFloor(), zffs, choosePatient.getZyhm());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("提醒").setMessage("是否要退出到登陆界面？").setPositiveButton("确定", (dialog12, which) -> {
                Intent intent = new Intent(getApplicationContext(), UserLoginActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                finish();
            }).setNegativeButton("取消", (dialog1, which) -> dialog1.dismiss());
            dialog.show();
        }
        return false;
    }

    public void changeDishNum(int groupPos, int detailPos) {
        int mCurrentNum = mMenuDetailList.get(groupPos).getDishList().get(detailPos).getOrderNum();
        if (mCurrentNum >= 0) {
            mMenuDetailList.get(groupPos).getDishList().get(detailPos).setOrderNum(mCurrentNum);
            mMenuDetailAdapter.setList(mMenuDetailList);
            setSelectedList();
        }
    }

    private void setSelectedList() {
        totalPrice = 0;
        for (MenuDetail menuDetail : mMenuDetailList
        ) {
            List<DC_CPXX> dishInfoList = menuDetail.getDishList();
            for (DC_CPXX dishInfo : dishInfoList
            ) {
                boolean found = false;
                for (SelectedDish selectedDish : mSelectedList
                ) {
                    if (!found && selectedDish.getID() == dishInfo.getID()) {
                        if (dishInfo.getOrderNum() > 0) {
                            selectedDish.setCPSL(dishInfo.getOrderNum());
                        } else {
                            mSelectedList.remove(selectedDish);
                        }
                        found = true;
                    }
                }
                if (dishInfo.getOrderNum() > 0) {
                    if (!found) {
                        SelectedDish dish = new SelectedDish(dishInfo);
                        mSelectedList.add(dish);
                    }
                }
            }
        }
        for (SelectedDish selectDish : mSelectedList
        ) {
            totalPrice += selectDish.getCPDJ() * selectDish.getCPSL();
        }
        mOrderSelectedAdapter.setList(mSelectedList);
        String total = "总计：￥ " + df.format(totalPrice);
        mTotalPrice.setText(total);
    }

    private void cleanSelected() {
        mSelectedList = new ArrayList<>();
        if (mMenuDetailList != null) {
            for (MenuDetail menuDetail : mMenuDetailList
            ) {
                List<DC_CPXX> dishInfoList = menuDetail.getDishList();
                for (DC_CPXX dishInfo : dishInfoList
                ) {
                    dishInfo.setOrderNum(0);
                }
            }
            mOrderSelectedAdapter.setList(mSelectedList);
            mMenuDetailAdapter.setList(mMenuDetailList);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        closeSearchView();
        switch (adapterView.getId()) {
            case R.id.order_dish_spinner:
                cleanSelected();
                setDietInfo(i);
                break;
            case R.id.order_bed_choose_spinner:
                new CountDownTimer(500, 250) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        choosePatient = doGetSelectPatientInfo(i);
                        setPatientInfo(choosePatient);
                    }
                }.start();

                break;
            case R.id.order_floor_choose_spinner:
                String chooseFloor = getMyApplication().getmFloorsNameList().get(i);
                getMyApplication().setChooseFloor(chooseFloor);
                changeFloor();
                break;
        }
    }

    @Override
    public void clearChoosePatientInfo() {
        super.clearChoosePatientInfo();
        choosePatient = null;
        setPatientInfo(null);
    }

    //配送日期显示、配送时间显示
    private void setDietInfo(int which) {
        mDDHCC = which + 1;
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) + 1);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM月dd日", Locale.CHINA);
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
        String tomorrow_title = sdf1.format(calendar.getTime());
        String tomorrow_delivery = sdf2.format(calendar.getTime());
        mDDHDate = sdf3.format(calendar.getTime());
        String diet_type = "";
        switch (which) {
            case 0:
                delivery_time = getMySharedPreferences().getString("order_breakfast", "06:30-07:30");
                diet_type = "早餐";
                break;
            case 1:
                delivery_time = getMySharedPreferences().getString("order_lunch", "11:00-12:00");
                diet_type = "午餐";
                break;
            case 2:
                delivery_time = getMySharedPreferences().getString("order_supper", "16:30-17:30");
                diet_type = "晚餐";
                break;
        }
        String dietTitle = String.format(getString(R.string.order_menu_title_3), tomorrow_title, diet_type);
        String deliveryText = getString(R.string.order_warn_text_2, tomorrow_delivery, delivery_time);
        mDietTitle.setText(dietTitle);
        mDeliveryText.setText(deliveryText);
        getDDHList();

        mResultList = cpxxArray.get(mDDHCC);
        if (mResultList != null && mResultList.size() > 0) {
            adapterData(mResultList);
            cleanSelected();
        } else {
            adapterData(new ArrayList<>());
            doGetMRCP(mDDHCC);
        }

    }

    private void doGetMRCP(int CC) {
        getMyApplication().setGettingCPXX(true);
        KLog.d("APE","获取菜品数据");
        showProgressDialog("获取菜品数据中");
        Observable<BaseResponse<List<MRCPXX>>> observable = RetrofitUtil.getInstence().getMRCP();
        mrcpObserver = new BaseObserver<List<MRCPXX>>() {
            @Override
            protected void onSuccees(BaseResponse<List<MRCPXX>> t) {
                cancelProgressDialog();
                List<MRCPXX> breakfastList = new ArrayList<>();
                List<MRCPXX> lunchList = new ArrayList<>();
                List<MRCPXX> dinnerList = new ArrayList<>();
                for (MRCPXX mrcpxx : t.getData()) {
                    if (mrcpxx.getCc() == 1) {
                        breakfastList.add(mrcpxx);
                    } else if (mrcpxx.getCc() == 2) {
                        lunchList.add(mrcpxx);
                    } else {
                        dinnerList.add(mrcpxx);
                    }
                }
                cpxxArray.put(1, breakfastList);
                cpxxArray.put(2, lunchList);
                cpxxArray.put(3, dinnerList);
                if (CC == 1) {
                    mResultList = breakfastList;
                } else if (CC == 2) {
                    mResultList = lunchList;
                } else {
                    mResultList = dinnerList;
                }
                int pos = CC - 1;
                mDishSpinner.setSelection(pos);
                adapterData(mResultList);
                cleanSelected();
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                KLog.d("APE", "获取菜品数据失败：" + e);
            }

            @Override
            protected void onCodeError(BaseResponse<List<MRCPXX>> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                getMyApplication().setGettingCPXX(false);
                KLog.d("APE", "获取菜品数据失败\n错误代码：" + t.getCode() + "\n错误信息：" + t.getMsg());
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mrcpObserver);

    }

    // 获取\初始化 今日订单列表
    private void getDDHList() {
        String sharedDate = getMySharedPreferences().getString("DDH_DATE", "");
        mDDHList = new ArrayList<>();
        if (Objects.requireNonNull(sharedDate).equals(mDDHDate)) {
            Set<String> ddhSet = getMySharedPreferences().getStringSet("DDH_SET", null);
            if (ddhSet != null) {
                mDDHList.addAll(ddhSet);
            }
        }
        getMySharedPreferences().edit().putString("DDH_DATE", mDDHDate).apply();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    // 饮食类型忌口检查
    private boolean YSLXCheck() {
        boolean hasJK = false;
        if (choosePatient != null) {
            String br_yslx = choosePatient.getYlsx();
            for (SelectedDish dish : mSelectedList) {
                if (!dish.getLX().contains(br_yslx)) {
                    hasJK = true;
                    dish.setJK(true);
                }
            }
        }
        return hasJK;
    }

    private void adapterData(List<MRCPXX> mResultList) {
        if (mResultList != null) {
            ArrayMap<String, List<DC_CPXX>> mMenuArray = new ArrayMap<>();
            Set<String> mTitleSet = new HashSet<>();

            for (MRCPXX mrcpxx : mResultList) {
                mTitleSet.add(mrcpxx.getCpfz());
                DC_CPXX cpxx = new DC_CPXX(mrcpxx);
                List<DC_CPXX> list;
                if (!mMenuArray.containsKey(mrcpxx.getCpfz())) {
                    list = new ArrayList<>();
                } else {
                    list = mMenuArray.get(mrcpxx.getCpfz());
                }
                Objects.requireNonNull(list).add(cpxx);
                mMenuArray.put(mrcpxx.getCpfz(), list);
            }

            List<String> mTitleList = new ArrayList<>(mTitleSet);
            Collections.sort(mTitleList, String::compareTo);
            mMenuDetailList = new ArrayList<>();
            for (ArrayMap.Entry<String, List<DC_CPXX>> entry : mMenuArray.entrySet()) {
                MenuDetail menuDetail = new MenuDetail();
                menuDetail.setGroupTitle(entry.getKey());
                menuDetail.setDishList(entry.getValue());
                mMenuDetailList.add(menuDetail);
            }
            Collections.sort(mMenuDetailList, (arg0, arg1) -> arg0.getGroupTitle().compareTo(arg1.getGroupTitle()));
            mGroupTitleAdapter.setList(mTitleList);
            mMenuDetailAdapter.setList(mMenuDetailList);
//            mSelectedList = new ArrayList<>();
//            mOrderSelectedAdapter.setList(mSelectedList);
        }
        getMyApplication().setGettingCPXX(false);
        doCancelLoad();
    }

    private void doSubmitOrder(String CWH, String ZYH, String SCSJ, String XDSJ, String
            DDH, String SDCP
            , String ZJG, String SCBZ, String LC, String zffs, String zyhm) {
//        showProgressDialog("提交订单中");
        XTGL xtgl = getMyApplication().getXtgl();
        StoredOrder stored_order = new StoredOrder(CWH, ZYH, choosePatient.getBrxm(), SCSJ, XDSJ, DDH, SDCP
                , ZJG, SCBZ, LC, zffs, zyhm, xtgl.getYhxm(), xtgl.getYhgh());
        stored_order.setDcr(Dcr);
        stored_order.setLxdh(Lxdh);
//        Call<String> saveDDXXCall = MyServiceUtil.saveDDXXCall(CWH, ZYH, SCSJ, XDSJ, DDH, "送餐", SDCP, 0, ZJG, SCBZ, BRXM);
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                cancelProgressDialog();
//                String result = response.body();
//                Gson gson = new Gson();
//                MessageReturn messageReturn = gson.fromJson(result, new TypeToken<MessageReturn>() {
//                }.getType());
//                if (messageReturn != null) {
//                    switch (messageReturn.getMsg()) {
//                        case "SUCCESS":
//                            Toast.makeText(getApplicationContext(), "订单提交成功！", Toast.LENGTH_SHORT).show();//提交成功，进入结算
//                            addDDH(DDH);
//                            break;
//                        case "EXIST":
//                            Toast.makeText(getApplicationContext(), "该订单号已存在，请勿重复提交！", Toast.LENGTH_SHORT).show();
//                            break;
//                    }
//                } else {
//                    Toast.makeText(getApplicationContext(), "订单提交失败,将自动保存", Toast.LENGTH_LONG).show();//提交成功，进入结算
//                    addSaveOrder(stored_order);
//                    addDDH(DDH);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                cancelProgressDialog();
//                Toast.makeText(getApplicationContext(), "订单提交失败,将自动保存", Toast.LENGTH_LONG).show();//提交成功，进入结算
        addSaveOrder(stored_order);
        addDDH(DDH);
//            }
//        };
//        saveDDXXCall.enqueue(callback);
    }

    private void addDDH(String newDDH) {
        mDDHList.add(newDDH);
        Set<String> set = new HashSet<>(mDDHList);
        getMySharedPreferences().edit().putStringSet("DDH_SET", set).apply();
        cleanSelected();
    }

    private void showSubmitDialog(boolean isJK) {
        cancelSubmitDialog();
        submitDialogFragment = new SubmitDialogFragment();
        submitDialogFragment.setJK(isJK);
        String lxdh = choosePatient.getLxdh();
        if (!lxdh.equals(choosePatient.getJtdh())) {
            lxdh += "," + choosePatient.getJtdh();
        }
        submitDialogFragment.setChoose_patient_lxdh(lxdh);
        submitDialogFragment.setStoredKWBZ(getMySharedPreferences().getString("storedKWBZ", ""));
        submitDialogFragment.show(getFragmentManager(), "submit");
    }

    private void cancelSubmitDialog() {
        if (submitDialogFragment != null && submitDialogFragment.getDialog() != null) {
            submitDialogFragment.getDialog().dismiss();
        }
    }

    public List<SelectedDish> getmSelectedList() {
        return mSelectedList;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mGroupTitleListView.setSelection(i);
        int y = 0;
        for (int j = 0; j < i; j++) {
            int n = mMenuDetailList.get(j).getDishList().size();
            y += n + 1;
        }
        layoutManager.setStackFromEnd(true);
        layoutManager.scrollToPositionWithOffset(y, 0);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if (!TextUtils.isEmpty(query)) {
            query = query.toUpperCase();
            doFilterList(query);
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
//        if (TextUtils.isEmpty(newText)) {
//            adapterData(mResultList);
//        }
        if (newText.equals("")) {
            doFilterList("");
        }
        return false;
    }

    private void doFilterList(String query) {
        List<MRCPXX> filterList = new ArrayList<>();
        if (query.equals("")) {
            filterList = mResultList;
        } else {
            for (MRCPXX mrcpxx : mResultList
            ) {
                if (mrcpxx.getPydm().contains(query)) {
                    filterList.add(mrcpxx);
                }
            }
        }
        if (filterList.size() > 0) {
            adapterData(filterList);
        } else {
            mSearchView.setQuery("", false);
            mSearchView.onActionViewCollapsed();
            Toast.makeText(getApplicationContext(), "无满足条件菜品!", Toast.LENGTH_SHORT).show();
        }

    }

    //口味选择对话框
    @SuppressLint("UseSwitchCompatOrMaterialCode")
    public static class SubmitDialogFragment extends DialogFragment implements View.OnClickListener {

        private TextView warnText;
        private Button submitBtn;
        private Button cancelBtn;
        private GridView tasteGridView;
        private LinearLayout tasteChooseLayout;
        private LinearLayout loadLayout;
        private ProgressBar loadProgressBar;
        private TextView loadTextView;
        private RadioGroup payMethod;
        private Switch jzycSwitch;
        private EditText lxdhEditText;

        private boolean isJK = false;//是否有忌口
        private String storedKWBZ;
        private boolean hasKWBZ = false;
        private List<String> kwbzList;//口味备注
        private String choose_patient_lxdh;
        private String show_lxdh;

        private BaseObserver<List<DC_KWBZ>> kwbzObserver;

        public void setChoose_patient_lxdh(String choose_patient_lxdh) {
            this.show_lxdh = choose_patient_lxdh.split(",")[0];
            this.choose_patient_lxdh = choose_patient_lxdh;
        }

        public void setJK(boolean JK) {
            isJK = JK;
        }

        public void setStoredKWBZ(String storedKWBZ) {
            this.storedKWBZ = storedKWBZ;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            getDialog().setTitle("口味选择");
            View dialogView = inflater.inflate(R.layout.dialog_taste_choose, container, false);
            onBindDialogUI(dialogView);
            TasteAdapter tasteAdapter = new TasteAdapter(getActivity());
            tasteAdapter.setList(((OrderMenuActivity) getActivity()).getmSelectedList());
            tasteGridView.setAdapter(tasteAdapter);
            submitBtn.setOnClickListener(this);
            cancelBtn.setOnClickListener(this);
            lxdhEditText.setText(show_lxdh);
            jzycSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
                lxdhEditText.setEnabled(b);
                if (b) {
                    lxdhEditText.setText("");
                } else {
                    lxdhEditText.setText(show_lxdh);
                }
            });

            if (isJK) {
                warnText.setText(getString(R.string.taste_choose_text_1));
            } else {
                warnText.setText(getString(R.string.taste_choose_text_2));
            }
            return dialogView;
        }

        @Override
        public void onStart() {
            super.onStart();
            Dialog dialog = getDialog();
            if (dialog != null) {
                DisplayMetrics dm = new DisplayMetrics();
                getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
                Window window = dialog.getWindow();
                if (window != null) {
                    window.setLayout((int) (dm.widthPixels * 0.6), ViewGroup.LayoutParams.WRAP_CONTENT);
                    if (!storedKWBZ.equals("")) {
                        doLoadKWBZ(storedKWBZ);
                    }
                    doGetKWBZ();
                }
            }
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            super.onDismiss(dialog);
            if (kwbzObserver != null) {
                kwbzObserver.doCancelRequest();
            }
        }

        private void doAddTastes(List<DC_KWBZ> tasteList) {
            loadLayout.setVisibility(View.GONE);
            submitBtn.setEnabled(true);
            kwbzList = new ArrayList<>();
            tasteChooseLayout.removeAllViews();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(5, 2, 5, 2);
            RadioGroup.LayoutParams radioLP = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.MATCH_PARENT);
            radioLP.setMargins(10, 2, 10, 2);
            for (int i = 0; i < tasteList.size(); i++) {
                kwbzList.add(i, "");
                RadioGroup radioGroup = new RadioGroup(getActivity());
                radioGroup.setPadding(5, 0, 5, 0);
                radioGroup.setGravity(Gravity.CENTER_VERTICAL);
                radioGroup.setLayoutParams(layoutParams);
                radioGroup.setOrientation(LinearLayout.HORIZONTAL);
                List<String> valueList = Arrays.asList(tasteList.get(i).getJtkw().split(","));
                for (int j = 0; j < valueList.size(); j++) {
                    RadioButton radioButton = new RadioButton(getActivity());
                    radioButton.setLayoutParams(radioLP);
                    radioButton.setText(valueList.get(j));
                    radioButton.setTextSize(14);
//                    radioButton.setButtonDrawable(0);//去掉圆圈
                    radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                    radioButton.setPadding(10, 3, 10, 3);
                    radioButton.setGravity(Gravity.CENTER);
                    radioButton.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.radiobtn_bg));
                    radioGroup.addView(radioButton);
                    if (j == 0) {
                        radioGroup.check(radioButton.getId());
                        kwbzList.set(i, valueList.get(j));
                    }
                    radioButton.setOnFocusChangeListener((v, hasFocus) -> {
                        if (hasFocus) {
                            radioGroup.check(radioButton.getId());
                        }
                    });

                }
                int finalI = i;
                radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
                    RadioButton radioButton = group.findViewById(checkedId);
                    if (radioButton != null) {
                        kwbzList.set(finalI, radioButton.getText().toString());
                    }

                });
                tasteChooseLayout.addView(radioGroup);
            }
        }

        private void onLoadFailed() {
            loadProgressBar.setVisibility(View.GONE);
            loadTextView.setText(getString(R.string.taste_choose_text_4));
        }

        private void doLoadKWBZ(String result) {
            Gson gson = new Gson();
            List<DC_KWBZ> mResultList = gson.fromJson(result, new TypeToken<List<DC_KWBZ>>() {
            }.getType());
            if (mResultList != null && mResultList.size() > 0) {
                hasKWBZ = true;
                doAddTastes(mResultList);
            } else {
                hasKWBZ = false;
                onLoadFailed();
            }
        }

        private void onBindDialogUI(View view) {
            warnText = view.findViewById(R.id.taste_choose_warn_text);
            submitBtn = view.findViewById(R.id.taste_choose_submit_btn);
            cancelBtn = view.findViewById(R.id.taste_choose_cancel_btn);
            tasteGridView = view.findViewById(R.id.taste_choose_selectdish_gridview);
            tasteChooseLayout = view.findViewById(R.id.taste_choose_type_layout);
            loadLayout = view.findViewById(R.id.taste_choose_loading_layout);
            loadProgressBar = view.findViewById(R.id.taste_choose_load_progressbar);
            loadTextView = view.findViewById(R.id.taste_choose_load_text);
            payMethod = view.findViewById(R.id.pay_method_rg);
            jzycSwitch = view.findViewById(R.id.jsyc_switch);
            lxdhEditText = view.findViewById(R.id.lxdh_edittext);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.taste_choose_submit_btn:
                    String lxdh = lxdhEditText.getText().toString();
                    if (jzycSwitch.isChecked()) {
                        if (!PhoneFormatCheckUtils.isPhoneLegal(lxdh)) {
                            ((OrderMenuActivity) getActivity()).showToast("电话号码格式不正确！");
                            lxdhEditText.requestFocus();
                            return;
                        } else {
                            ((OrderMenuActivity) getActivity()).setLxdh(lxdh);
                        }
                    } else {
                        ((OrderMenuActivity) getActivity()).setLxdh(choose_patient_lxdh);
                    }
                    StringBuilder kwbz = new StringBuilder();
                    if (kwbzList != null && kwbzList.size() > 0) {
                        for (String str : kwbzList
                        ) {
                            if (kwbz.toString().equals("")) {
                                kwbz.append(str);
                            } else {
                                kwbz.append(",").append(str);
                            }
                        }
                    }
                    String zffs = "";
                    switch (payMethod.getCheckedRadioButtonId()) {
                        case R.id.pay_jz:
                            zffs = "jz";
                            break;
                        case R.id.pay_zfb:
                            zffs = "zfb";
                            break;
                        case R.id.pay_wx:
                            zffs = "wx";
                            break;
                    }
                    String dcr = jzycSwitch.isChecked() ? "家属" : "患者";
                    ((OrderMenuActivity) getActivity()).setDcr(dcr);
                    ((OrderMenuActivity) getActivity()).setZffs(zffs);
                    ((OrderMenuActivity) getActivity()).setDDKWBZ(kwbz.toString());
                    ((OrderMenuActivity) getActivity()).doSaveOrSubmitNewOrder();
                    getDialog().dismiss();

                    break;
                case R.id.taste_choose_cancel_btn:
                    getDialog().dismiss();
                    break;
            }
        }

        private void doGetKWBZ() {
            Observable<BaseResponse<List<DC_KWBZ>>> observable = RetrofitUtil.getInstence().getKWBZ();
            kwbzObserver = new BaseObserver<List<DC_KWBZ>>() {
                @Override
                protected void onSuccees(BaseResponse<List<DC_KWBZ>> t) {
                    if (t.getData().size() > 0) {
                        hasKWBZ = true;
                        doAddTastes(t.getData());
                    } else {
                        hasKWBZ = false;
                        onLoadFailed();
                    }
                    Gson gson = new Gson();
                    String result = gson.toJson(t.getData());
                    ((OrderMenuActivity) getActivity()).getMySharedPreferences().edit().putString("storedKWBZ", result).apply();
                }

                @Override
                protected void onFailure(Throwable e, boolean isNetWorkError) {
                    KLog.d("APE", "获取数据失败：" + e);
                    if (!hasKWBZ) {
                        onLoadFailed();
                    }
                }

                @Override
                protected void onCodeError(BaseResponse<List<DC_KWBZ>> t) {
                    super.onCodeError(t);
                    KLog.d("APE", "获取数据失败\n错误代码：" + t.getCode() + "\n错误信息：" + t.getMsg());
                    if (!hasKWBZ) {
                        onLoadFailed();
                    }
                }

            };
            observable
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(kwbzObserver);
        }
    }

}
